<template>
	<div class="edu-page-warp">
		<inner-breadcrumb v-model="pathKey" :path="path" v-show="pathKey!='main'"></inner-breadcrumb>
		<template v-if="pathKey=='main'">
			<condition-card @reset="reset" @search="onSubmit" label-width="120px">
				<el-row :gutter="24" style="height: 50px;">
					<el-col :span="8">
						<el-form-item :label="$t('course.college')">
							<el-select v-model="queryForm.college" style="width: 100%;" clearable>
								<el-option
									v-for="item in options.college"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item :label="$t('label.trainingLevel')" v-if="isGraduate">
							<el-select v-model="queryForm.trainingLevel" style="width: 100%;" clearable>
								<el-option
									v-for="item in options.trainingLevel"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="isGraduate">
						<el-form-item :label="$t('course.courseProperty')">
							<el-select v-model="queryForm.nature" style="width: 100%;" @change="changeNatureForm" clearable>
								<el-option
									v-for="item in options.nature"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="isUnderGraduate">
						<el-form-item :label="$t('course.isPublicChooseCourse')">
							<el-select v-model="queryForm.isElective" style="width: 100%;" clearable>
								<el-option
									v-for="item in options.isElective"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="24" v-if="isGraduate">
					<el-col :span="8">
						<el-form-item :label="$t('course.courseCategory')">
							<el-select
								v-model="queryForm.label"
								style="width: 100%;"
								:placeholder="$t('course.selectProperty')"
								clearable
							>
								<el-option
									v-for="item in options.newLabel"
									:key="item.value"
									:label="item.label"
									:value="item.value"
									:style="{textIndent:item.indent+'px'}"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item :label="$t('course.teachingLanguage')">
							<el-select v-model="queryForm.teachingLanguage" clearable style="width: 100%;">
								<el-option
									v-for="item in options.teachingLanguage"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item :label="$t('course.enabled')">
							<el-select v-model="queryForm.enabled" style="width: 100%;" clearable>
								<el-option
									v-for="item in options.enabled"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="24" style="height: 50px;" v-if="isGraduate">
					<el-col :span="8">
						<el-form-item :label="$t('开课学期')">
								<DictSelect
                                v-model="queryForm.term"
                                :data="options.term"
								:plzSelect="true"
                            ></DictSelect>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item :label="$t('是否跨院系课程')">
								<DictSelect
                                v-model="queryForm.crossCollege"
                                :data="options.enabled"
                                :plzSelect="true"
                            ></DictSelect>
						</el-form-item>
						
					</el-col>
				</el-row>
			</condition-card>
			<el-card shadow="never">
				<div class="edu-page-title" style="margin-bottom: 16px">{{$t("course.CourseMaintain")}}</div>
				<div class="edu-opertion-bar" v-if="isEnable" style="margin-bottom: 16px">
					<div class="float-left">
						<el-input
							v-model="queryForm.condition"
							:placeholder="$t('course.inputCourseTip')"
							style="width:240px"
							@keyup.enter.native="onSubmit"
						>
							<i
								class="el-icon-search"
								slot="suffix"
								style="margin-top:10px;cursor:pointer"
								@click="onSubmit"
							></i>
						</el-input>
					</div>
					<!--课程维护时间-->
					<div v-if="courseTimes&&courseTimes.length>0" class="time">
						<div>课程维护开放时间：</div>
						<div>
							<span v-for="(ct,index_) in courseTimes" :key="'time'+index_">
								{{ct.startTime}} ~ {{ct.endTime}} 
							</span>
						</div>
					</div>
					<div class="float-right">
						<el-dropdown v-if="isUnderGraduate" @command="handleCommand" style="margin-right:8px">
							<el-button>
								{{$t("message.import")}}
								<i class="el-icon-arrow-down el-icon--right"></i>
							</el-button>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item command="import">{{$t("message.import")}}</el-dropdown-item>
								<el-dropdown-item command="download">{{$t("course.downTemplate")}}</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
						<el-button  @click="exportExcel" v-if="!this.global.isStudent && isGraduate ">{{$t("message.export")}}</el-button>
						<el-button  @click="exportExcel" type="primary" v-if="!isGraduate ">{{$t("message.export")}}</el-button>
						<!-- 	<el-button v-if="isUnderGraduate" @click="importFiles">{{$t("message.import")}}</el-button>
						<el-button v-if="isUnderGraduate" @click="downFiles">{{$t('message.down')}}</el-button>-->
						<el-button @click="upload" v-if="!isUnderGraduate">{{$t('message.upload')}}</el-button>
						<el-button type="primary" @click="showAddDialog" v-if="this.global.isAdmin">{{$t("message.add")}}</el-button>
					</div>
				</div>				
				<edu-table
					:data="courses"
					@page-change="handleCurrentChange"
					:total="queryForm.total_"
					:pageSize="queryForm.pageSize_"
					:current-page="queryForm.pageNum_"
					@selection-change="chooseCourse"
				>
					<edu-table-column :label="$t('course.college')" prop="college" width="200"/>
					<edu-table-column :label="$t('course.courseCode')" prop="code" width="120"/>
					<edu-table-column :label="$t('course.courseName')" width="240">
						<template slot-scope="props">
							<span>{{getNameByLanguage(props.row)}}</span>
						</template>
					</edu-table-column>
					<edu-table-column :label="$t('course.score')" prop="credits" :width="isGraduate?65:null"/>
					<edu-table-column :label="$t('courses.classHour')" prop="period" :width="isGraduate?65:null" />
					<edu-table-column :label="$t('course.term')" v-if="isGraduate" prop="term" width="80"/>
					<edu-table-column :label="$t('course.courseProperty')" v-if="isGraduate" prop="nature" />
					<edu-table-column :label="$t('label.totalWeek')" v-if="isUnderGraduate" prop="weeks" />
					<edu-table-column :label="$t('course.weekHour')" v-if="isUnderGraduate" prop="weekHour" />
					<edu-table-column :label="$t('是否使用')" v-if="isGraduate">
						<template slot-scope="props">{{props.row.enabled == null?"":(props.row.enabled == 1?'是':'否')}}</template>
					</edu-table-column>
					<edu-table-column :label="$t('是否跨院系课程')" v-if="isGraduate" width="130">						
						<template slot-scope="props">{{props.row.crossCollege == null?"":(props.row.crossCollege == 1?'是':'否')}}</template>
					</edu-table-column>
					<edu-table-column :label="$t('course.ofScheme')" v-if="isGraduate" width="120">						
						<template slot-scope="props">
							<span slot="reference" v-if="props.row.status==3">
								<el-button
									type="text"
									size="mini"
									@click="queryScheme(props.row.code)"
								>{{$t('course.ofScheme')}}</el-button>
							</span>
							<span slot="reference" v-else>{{$t('course.ofScheme')}}</span>
						</template>
					</edu-table-column>
					<edu-table-column :label="$t('message.operating')" width="140" fixed="right">
						<template slot-scope="props">
							<el-button
								type="text"
								@click="courseEdit(props.row, 'detail')"
								size="mini"
							>{{$t('shortTermApprove.check')}}</el-button>
							<el-button
								type="text"
								@click="courseEdit(props.row, 'edit')"
								size="mini"
							>{{$t('message.edit')}}</el-button>
							<el-button type="text" @click="courseDelete(props.row)" size="mini">{{$t('message.delete')}}</el-button>
						</template>
					</edu-table-column>
				</edu-table>
			</el-card>

			<!--本科生添加/编辑对话框-->
			<el-dialog
				:title="dialogTitle"
				width="1000px"
				class="gCourseAddDialog2"
				:visible.sync="showUnderGraduateDialog"
				@close="resetUnderFormValidate()"
				:close-on-click-modal="false"
				v-drag-dialog
			>
				<el-form
					:model="underGraduateCourseForm"
					label-position="right"
					label-width="100px"
					:rules="underGraduateCourseRules"
					ref="underGraduateCourseForm"
					label-suffix=":"
				>
					<el-row>
						<el-col :span="12">
							<el-form-item :label="$t('course.college')" prop="college">
								<el-select
									v-model="underGraduateCourseForm.college"
									:disabled="readOnly"
									@change="reSetCode"
									style="width: 100%;"
								>
									<el-option
										v-for="item in options.college"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item :label="$t('course.courseCode')" v-if="underAuto">
								<el-input
									disabled
									v-model="underGraduateCourseForm.code"
									:placeholder="$t('common.pla.pleaseInput')"
									type="text"
									maxlength="100"
								/>
							</el-form-item>
							<el-form-item :label="$t('course.courseCode')" prop="code" v-else>
								<el-input
									:disabled="isUpdate"
									:placeholder="$t('common.pla.pleaseInput')"
									v-model="underGraduateCourseForm.code"
									type="text"
									maxlength="32"
									style="width: 63%;"
									ref="courseFormCode2"
								/>
								<el-button
									:disabled="isUpdate"
									v-if="!readOnly"
									type="text"
									@click="autoCode"
									style="width: 35%;font-size: 14px;"
								>{{$t("course.autoAllocation")}}</el-button>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item :label="$t('message.name')" prop="name">
								<el-input
									v-model="underGraduateCourseForm.name"
									maxlength="50"
									:disabled="readOnly"
									:placeholder="$t('common.pla.pleaseInput')"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item :label="$t('message.nameEn')" prop="nameEn">
								<el-input
									v-model="underGraduateCourseForm.nameEn"
									maxlength="300"
									:placeholder="$t('common.pla.pleaseInput')"
									:disabled="readOnly"
								/>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item :label="$t('course.score')" prop="credits">
								<el-input
									v-model="underGraduateCourseForm.credits"
									maxlength="10"
									:disabled="readOnly"
									:placeholder="$t('common.pla.pleaseInput')"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item :label="$t('course.isPublicChooseCourse')" prop="isElective">
								<el-select
									v-model="underGraduateCourseForm.isElective"
									style="width: 100%;"
									:disabled="readOnly"
								>
									<el-option
										v-for="item in options.isElective"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item :label="$t('course.weekHour')" prop="weekHour">
								<el-input
									v-model="underGraduateCourseForm.weekHour"
									maxlength="10"
									:placeholder="$t('common.pla.pleaseInput')"
									:disabled="readOnly"
									@input="calUnderGraduatePeriod"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item :label="$t('label.totalWeek')" prop="weeks">
								<el-input
									v-model="underGraduateCourseForm.weeks"
									maxlength="5"
									:placeholder="$t('common.pla.pleaseInput')"
									:disabled="readOnly"
									@input="calUnderGraduatePeriod"
								/>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item :label="$t('courses.classHour')" prop="period">
								<el-input
									v-model="underGraduateCourseForm.period"
									maxlength="10"
									:placeholder="$t('common.pla.pleaseInput')"
									:disabled="readOnly"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="readOnly">
							<el-form-item :label="$t('courseSummary.createTime')" >
								<el-input
									v-model="underGraduateCourseForm.createdAt"
									:disabled="true"
								/>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row v-if="readOnly">
						<el-col :span="12">
							<el-form-item label="修改时间" >
								<el-input
									v-model="underGraduateCourseForm.updatedAt"
									:disabled="true"
								/>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="24">
							<div class="float-right">
								<el-button v-if="!readOnly" @click="cancelUnderGraduateCourse">{{$t("message.cancel")}}</el-button>
								<el-button
									v-if="!readOnly"
									type="primary"
									@click="saveUnderGraduateCourse"
								>{{$t("message.save")}}</el-button>
								<el-button v-if="readOnly" @click="cancelUnderGraduateCourse">{{$t("message.close")}}</el-button>
							</div>
						</el-col>
					</el-row>
				</el-form>
			</el-dialog>
		</template>

		<edu-dialog
			:title="$t('course.underGraduateCourseImport')"
			width="500px"
			ref="uploadDialog"
			@close="clearFiles"
			@confirm="uploadFile"
		>
			<el-form label-width="85px">
				<el-row>
					<el-form-item>
						<el-upload
							ref="upload"
							:data="{}"
							:on-success="uploadDone"
							:before-upload="beforeAvatarUpload"
							:before-remove="beforeRemove"
							:on-error="onError"
							:auto-upload="false"
							:multiple="false"
							:on-change="(file, fileList)=>{this.fileList = fileList}"
							:limit="1"
							:accept="'application/vnd.ms-excel'"
							action="api/cultureservice/courses/import"
						>
							<el-button slot="trigger" size="small" type="primary">{{$t('label.selectFile')}}</el-button>
							<!-- 	<el-button
								slot="trigger"
								@click.stop.native="downFiles"
								size="small"
							>{{$t("course.downTemplate")}}</el-button>-->
							<div slot="tip" class="el-upload__tip">{{$t('culture.profession.uploadXLSFileOnly')}}</div>
						</el-upload>
					</el-form-item>
				</el-row>
			</el-form>
		</edu-dialog>
		<el-dialog
			:title="$t('course.courseOutlineTemplateUpload')"
			width="550px"
			class="gCourseAddDialog"
			:visible.sync="showUploadDialog"
			:close-on-click-modal="false"
			@close="templateClearFiles"
			v-drag-dialog
		>
			<el-form label-position="top" label-width="400px">
				<el-row class="file-list">
					<el-col>
						<div class="item-group">
							<label class="secondary-text label">{{$t("course.courseOutlineTemplate")}}：</label>
							<div class="display-inline-block">
								<el-upload
									ref="myUpload"
									:before-upload="beforeTemplateUploadUpload"
									:before-remove="beforeTemplateUploadRemove"
									:headers="{'X-Token': $store.state.session.sessionid}"
									:data="{bucketname: 'face', folderpath: 'file'}"
									:on-success="handleAvatarSuccess"
									:on-change="(file, fileList)=>{this.templateList = fileList}"
									class="upload-demo"
									action="/api/commonservice/obsfile/uploadfile"
									:accept="'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'"
									multiple="false"
									limit="1"
									:auto-upload="false"
								>
									<el-button size="small" type="primary">{{$t("common.btn.clickUpload")}}</el-button>
									<div
										slot="tip"
										class="el-upload__tip"
									>{{this.$t("common.upload.uploadWORDFileOnly")}}{{$t("common.upload.sizeLimit3M")}}</div>
								</el-upload>
							</div>
						</div>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button  @click="cancelUploadDialog">{{$t("message.cancel")}}</el-button>
				<el-button  :disabled="uploading" type="primary" @click="saveUpload">{{$t("message.save")}}</el-button>
			</div>
		</el-dialog>

		<CourseOperation
			v-if="pathKey=='check' || pathKey=='add' || pathKey=='edit' "
			:pathKey="pathKey"
			:options="options"
			:courseForm="courseForm"
			:heardTitle="heardTitle"
			:managerDeptId="managerDeptId"
			:auto="auto"
			@back="pathKey='main';onSubmit();"
			:isMaintain="true"
		></CourseOperation>

		<QuerySchemesComponent
			v-if="pathKey=='schemes'"
			:code="code"
			:schemeForm="schemeForm"
			:heardTitle="heardTitle"
			@back="pathKey='main'"
		></QuerySchemesComponent>

		<edu-dialog
			title="导入结果"
			width="800px"
			:visible.sync="importDialogVisible"
		>
			<div>
				<span style="color:green">导入成功</span>，其中已存在的课程<span style="color:red">{{importExistCourseList.length}}</span>门，如下:
			</div>
			<el-table  :data="importExistCourseList" style="margin-top:10px">
				<el-table-column
					prop="name"
					:label="$t('message.name')"
				/>
				<el-table-column
					prop="nameEn"
					:label="$t('message.nameEn')"
				/>
				<el-table-column
					prop="collegeI18n"
					:label="$t('course.college')"
				/>
				<el-table-column
					prop="weekHour"
					:label="$t('course.weekHour')"
				/>
				<el-table-column
					prop="weeks"
					:label="$t('label.totalWeek')"
				/>
				<el-table-column
					prop="credits"
					:label="$t('course.score')"
				/>
			</el-table>
			<div slot="buttons">
				<el-button @click="importDialogVisible=false">{{$t('message.close')}}</el-button>
			</div>
		</edu-dialog>
	</div>
</template>
<script>
import {
	getCourseList,
	handleCourseCategory,
	queryScheme,
	autoCode,
	upload,
	getCollegeids
} from "common/src/api/courseTemplate";
import {
	addCourse,
	editCourse,
	deleteCourse,
	getCourseById,
	generateExcel,
	getExcelPath,
	apporoveCourse,
	checkCourseName,
	getDownloadUrl,
	getCoursesReportStatus,
	getFacultys,
	queryListByCurrentUser
} from "common/src/api/resource/course";
import { findListByFaculty } from "common/src/api/resource/teachers";
import { queryDic } from "common/src/api/dictionary";
import { pingSession } from "common/src/api/session";
import UTILS from "common/src/utils/utils";
import CourseOperation from "./component/CourseOperation";
import QuerySchemesComponent from "./component/QuerySchemesComponent";
import examinationStudentsApi from "common/src/api/welcomeService/examinationStudents";
import mixin from 'common/src/mixins/index';

var defaultCourseForm = {
	code: "", //课程编码
	name: "", //课程名称
	nameEn: "", //课程名称英文
	college: "", //学院
	trainingLevel: "", //培养层次
	formLearning: "", //学习形式(课程类型)
	credits: "", //学分
	period: "", //课时
	label: "", //课程分类
	isElective: "",
	outlineWriter: "",
	outlineWriterEn: "",
	outlineApprover: "",
	naturePurpose: "",
	basicRequire: "",
	schedule: "", //获取课程内容与学时分配
	scheduleEn: "", //课程内容与学时分配(英文)
	experiment: "", //实验及实践性环节
	experimentEn: "",
	establishOn: "",
	introductionCourse: "", //简介
	engIntroductionCourse: "", //英文简介
	crossCollege: 0, //是否跨学院
	crossTrainingLevel: 0, //是否本研互选（1是0否）
	cause: "",
	remark: "",
	term: "", //研究生字段，开课学期
	nature: "", //研究生字段，课程性质
	scoreType: "", //研究生字段，成绩类型
	teachingLanguage: "", //研究生字段，授课语言
	majorList: [], //研究生字段，专业中文
	majorTextI18n:null,
	majorEnList: [], //研究生字段，专业英文
	enabled: 1, //研究生字段，课程使用状态
	crossTerm: 0, //研究生字段，是否跨学期
	assessmentMode: "", //考试方式,
	headTeacher: "", //课程负责人
	teachersList: [], //其他讲课人
	teachModeI18n:"",
	teachModeList: [], //教学方式
	precourse: "", //预修课程
	precourseEn: "", //预修课程(英文)Prerequisite
	teacherTermInfo: "", //教师团队介绍
	requirement: "", //教学目标与要求
	requirementEn: "" //教学目标与要求英文
};
export default {
	name: "courseManage",
	mixins: [mixin],
	components: {
		CourseOperation,
		QuerySchemesComponent
	},
	data() {
		return {
			pathKey: "main",
			path: {
				label: this.$t("courses.courseManagement"),
				key: "belong",
				disable: true,
				children: [
					{
						label: this.$t("courses.maintenance"),
						key: "main",
						children: [
							{
								label: this.$t("courses.courseDetails"),
								key: "check"
							},
							{
								label: this.$t("courses.addCourse"),
								key: "add"
							},
							{
								label: this.$t("courses.editCourse"),
								key: "edit"
							},
							{
								label: this.$t("courses.courseSchemes"),
								key: "schemes"
							}
						]
					}
				]
			},
			underAuto: true,
			auto: false,
			isUnderGraduate: false,
			isGraduate: false,
			isUpdate: false,
			courseStatus: {
				DISABLE: 0,
				DRAFT: 1,
				CHECKING: 2,
				PUBLISH: 3
			},
			queryForm: {
				teachingLanguage: "",
				college: "", //学院
				trainingLevel: "", //培养层次
				formLearning: "", //学习形式(课程类型)
				nature: "", //课程性质
				isElective: "", //公共选修课
				label: "", //课程分类
				enabled: "", //是否使用
				condition: "", //课程代码或课程名称
				status: 3,
				pageSize_: 20,
				pageNum_: 1,
				total_: 0,
				managerDeptId: "",
				term:"",//开课学期
				crossCollege:""//是否跨院系课程
			},
			underGraduateCourseForm: {
				code: "",
				college: "",
				trainingLevel: "1",
				name: "",
				nameEn: "",
				credits: "",
				isElective: "",
				weekHour: "",
				weeks: "",
				period: "",
				checked: true,
				managerDeptId: 1,
				createdAt:null,
				updatedAt:null
			},
			autoCodeInfo: {
				trainingLevel: "",
				college: "",
				managerDeptId: ""
			},
			schemeForm: {
				code: "",
				pageSize_: 20,
				pageNum_: 1,
				total_: 0
			},
			courseForm: JSON.parse(JSON.stringify(defaultCourseForm)),
			underGraduateCourseRules: {
				code: [
					{
						required: true,
						message: this.$t("course.clickAutoGenerateCode"),
						trigger: "blur"
					}
				],
				name: [
					{
						required: true,
						trigger: "blur",
						validator:this.checkName
					},
					{
						validator: this.notBlank,
						trigger: "blur"
					}
				],
				nameEn: [
					{
						required: true,
						message: this.$t("course.inputCourseName"),
						trigger: "blur"
					},
					{
						validator: this.notBlank,
						trigger: "blur"
					}
				],
				college: [
					{
						required: true,
						message: this.$t("course.selectCollege"),
						trigger: "blur"
					}
				],
				trainingLevel: [
					{
						required: true,
						message: this.$t("course.selectTrainingLevel"),
						trigger: "blur"
					}
				],
				period: [
					{
						required: true,
						message: this.$t("course.inputStudyTime"),
						trigger: "blur"
					},
					{
						validator: this.doubleReg,
						trigger: "blur"
					},
					{
						validator: this.notBlank,
						trigger: "blur"
					}
				],
				weekHour: [
					{
						required: true,
						message: this.$t("course.inputWeekStudyTime"),
						trigger: "blur"
					},
					{
						validator: this.doubleReg,
						trigger: "blur"
					},
					{
						validator: this.notBlank,
						trigger: "blur"
					}
				],
				weeks: [
					{
						required: true,
						message: this.$t("course.inputWeekNum"),
						trigger: "blur"
					},
					{
						validator: this.doubleReg,
						trigger: "blur"
					},
					{
						validator: this.notBlank,
						trigger: "blur"
					}
				],
				credits: [
					{
						required: true,
						message: this.$t("course.inputCourseScore"),
						trigger: "blur"
					},
					{
						validator: this.doubleReg,
						trigger: "blur"
					},
					{
						validator: this.notBlank,
						trigger: "blur"
					}
				],
				isElective: [
					{
						required: true,
						message: this.$t("course.selectIsPublicChooseCourse"),
						trigger: "blur"
					}
				]
			},
			options: {
				college: [],
				trainingLevel: [],
				formLearning: [],
				nature: [], //课程性质
				isElective: [], //公共选修课，（1或0)
				label: [], //课程分类
				newLabel: [],
				tableLabel: [],
				crossCollege: [], //是否跨学院（1是0否）
				crossTrainingLevel: [], //是否本研互选（1是0否）
				term: [],
				scoreType: [], //成绩类型
				teachingLanguage: [], //授课类型
				enabled: [], //研究生字段，课程使用状态
				crossTerm: [], //研究生字段，是否跨学期
				dialogLabelId: [], //弹框的课程分类
				assessmentMode: [], //考试方式
				majorList: [],
				teacherList: [],
				departments: [], //部门
				teachModeList: [] //教学方式
			},
			courses: [], //课程列表
			chooseCourses: [], //选中课程列表
			schemes: [], //培养方案列表
			teachModeList: [],
			showDialog: false,
			showSchemeDialog: false,
			editCourseId: "", //当前编辑课程Id
			dialogTitle: "",
			isEnable: false,
			readOnly: false,
			showUploadDialog: false,
			majorDataEn: "",
			showUnderGraduateDialog: false, //本科生对话框
			checking: false,
			headTeacherCondition: null,
			teacherCondition: null,
			fileList: [],
			uploading:false,
			showRemoveConfirm:true,
			templateList:null,
			importDialogVisible:false,
			importExistCourseList:[],
			courseTimes:null
		};
	},
	mounted() {
		let user =
			this.$store.state.session.user ||
			JSON.parse(localStorage.getItem("user"));
		if (user && user.currentManageDptId) {
			this.isGraduate = user.currentManageDptId != "1";
			this.isUnderGraduate = user.currentManageDptId == "1";
		}
		this.init();
		//研究生教务员时获取课程维护时间
		if(this.isGraduate&&this.global.isAcdemicDean&&!this.global.isAdmin){
			queryListByCurrentUser().then(res=>{
				if(res.code==200&&res.data){
					let faculty=this.global.currentUser.faculty;					
					if(!faculty){
						return;
					}
					res.data.forEach(row=>{						
						let codes=row.collegeCodes?row.collegeCodes.split(','):[];
						if(!codes.includes(faculty)){
							row.isDelete=true;
						}
					})
					this.courseTimes=res.data.filter(row=>!row.isDelete);
				}
			})
		}
	},
	methods: {
		init() {
			let yes = {
					label: this.$t("message.yes"),
					value: 1
				},
				no = {
					label: this.$t("message.no"),
					value: 0
				};
			this.options.isElective.push(yes);
			this.options.isElective.push(no);
			this.options.crossCollege.push(yes);
			this.options.crossCollege.push(no);
			this.options.crossTrainingLevel.push(yes);
			this.options.crossTrainingLevel.push(no);
			this.options.enabled.push(yes);
			this.options.enabled.push(no);
			this.options.crossTerm.push(yes);
			this.options.crossTerm.push(no);
			//筛选条件字典查询
			let data = {
				lang: this.$store.getters.language || "cn",
				type: "allChild",
				keys: [
					"X_PYCC",
					//"X_YX",
					"X_XXXS",
					"X_CJJL",
					"X_SKYY",
					"X_KKXQ",
					"X_KSLX",
					"G_ZY",
					"X_KCXZ",
					"X_KCFL",
					"X_JXFS"
				]
			};
			queryDic(data).then(res => {
				if (res.code == 200) {
					let cObj = {};
					// //学院ids
					// let collegeids = [];
					// getCollegeids().then(response => {
					//     if (response.code == 200) {
					//         collegeids = response.data;
					//     }
					// });
					// if (collegeids.length > 0) {
					//     Object.keys(res.data["X_YX"]).forEach(key => {
					//         if (collegeids.indexOf(key) != -1) {
					//             cObj[key] = res.data["X_YX"][key];
					//         }
					//     });
					//     res.data["X_YX"] = cObj;
					// }
					UTILS.fillSelect(
						{
							trainingLevel: "X_PYCC",
							//college: "X_YX",
							formLearning: "X_XXXS",
							scoreType: "X_CJJL",
							teachingLanguage: "X_SKYY",
							term: "X_KKXQ",
							assessmentMode: "X_KSLX",
							majorList: "G_ZY",
							nature: "X_KCXZ",
							label: "X_KCFL",
							teachModeList: "X_JXFS"
						},
						res.data,
						this.options
					);
					this.isEnable = true;
				}
			});
			//查询开课学院
			getFacultys(this.isGraduate).then(res => {
				if (res.code == 200) {
					let depts =res.data.filter(c => c.deptCode != "-10000");
					this.options.college = depts;
					this.options.college.forEach(c => {
						c.value = c.deptCode;
						c.label =
							"en" == this.$store.getters.language
								? c.deptNameEn
								: c.deptName;
					});
				}
			});
			this.onSubmit();
			//查询专业的英文
			let majorDataEn = {
				lang: "en",
				type: "allChild",
				keys: ["G_ZY"]
			};
			queryDic(majorDataEn).then(res => {
				if (res.code == 200) {
					this.majorDateEn = res.data["G_ZY"];
				}
			});
		},
		reset() {
			this.options.newLabel.length = 0;
			this.queryForm.college = "";
			this.queryForm.trainingLevel = "";
			this.queryForm.formLearning = "";
			this.queryForm.nature = "";
			this.queryForm.isElective = "";
			this.queryForm.label = "";
			this.queryForm.condition = "";
			this.queryForm.enabled = "";
			this.queryForm.teachingLanguage = "";
			this.queryForm.term ="";
			this.queryForm.crossCollege =""
			this.onSubmit();
		},
		doubleReg(rule, value, callback) {
			let number = new Number(value);
			if (isNaN(number)) {
				callback(new Error(this.$t("course.mustInputNumber")));
			} else {
				callback();
			}
		},
		onSubmit() {
			this.getCourseList();
		},
		upload() {
			this.showUploadDialog = true;
			this.uploading=false;
			this.templateList=null;
		},
		changeNatureForm(val) {
			this.options.newLabel = [];
			this.queryForm.label = "";
			let obj = [];
			let labels = this.options.label;
			labels.forEach(item => {
				if (val == "1") {
					if (
						item.value == "01" ||
						item.value == "02" ||
						item.value == "03" ||
						item.value == "07"
					) {
						obj.push({ label: item.label, value: item.value });
					}
				} else if (val == "2") {
					if (
						item.value == "04" ||
						item.value == "05" ||
						item.value == "06" ||
						item.value == "07"
					) {
						obj.push({ label: item.label, value: item.value });
					}
				} else {
					if (item.value == "08" || item.value == "09") {
						obj.push({ label: item.label, value: item.value });
					}
				}
			});
			this.options.newLabel = obj;
		},
		changeNatureEdit(val) {
			this.options.tableLabel = [];
			let obj = [];
			let labels = this.options.label;
			labels.forEach(item => {
				if (val == "1") {
					if (
						item.value == "01" ||
						item.value == "02" ||
						item.value == "03" ||
						item.value == "07"
					) {
						obj.push({ label: item.label, value: item.value });
					}
				} else if (val == "2") {
					if (
						item.value == "04" ||
						item.value == "05" ||
						item.value == "06" ||
						item.value == "07"
					) {
						obj.push({ label: item.label, value: item.value });
					}
				} else {
					if (item.value == "08" || item.value == "09") {
						obj.push({ label: item.label, value: item.value });
					}
				}
			});
			this.options.tableLabel = obj;
		},
		//改变学院，培养层次重置课程code
		reSetCode(val) {
			this.underGraduateCourseForm.code = "";
			//this.courseForm.code = "";
		},
		formatDate(timenumber) {
			return moment(timenumber).format("YYYY-MM-DD");
		},
		handleCurrentChange(val) {
			this.queryForm.pageSize_ = val.pageSize;
			this.queryForm.pageNum_ = val.pageNum;
			this.getCourseList();
		},

		// handleSchemeCurrentChange(val) {
		// 	this.schemeForm.pageSize_ = val.pageSize;
		// 	this.schemeForm.pageNum_ = val.pageNum;
		// 	this.queryScheme();
		// },
		handleAvatarSuccess(response, file, fileList) {			
			if (response && response.data) {
				upload(response.data[file.name].objectkey,this.queryForm.managerDeptId).then(res => {
				if (res.code == 200) {
					this.$message({
						type: "success",
						message: this.$t("message.saveSuccess")
					});
					this.showUploadDialog = false;
				} else {
					this.uploading=false;
					throw response.code;
				}
				
			});
			}
		},
		//获取课程列表
		getCourseList() {
			getCourseList(this.queryForm).then(response => {
				if (response.code == 200) {
					this.courses = response.data.list;
					this.queryForm.total_ = response.data.total_;
				} else {
					throw response.code;
				}
			});
		},
		chooseCourse(val) {
			this.chooseCourses = val;
		},
		//课程编辑
		courseEdit(row, type) {
			if (type == "edit") {
				this.dialogTitle = this.$t("course.updateCourse");
				this.readOnly = false;
				this.underAuto = true;
				this.isUpdate = false;
			} else if (type == "detail") {
				this.dialogTitle = this.$t("course.courseDetails");
				this.readOnly = true;
				this.underAuto = true;
				this.isUpdate = true;
			}
			this.editCourseId = row.id;
			//获取该课程详细信息
			getCourseById(this.editCourseId).then(response => {
				if (response.code == 200) {
					if (this.queryForm.managerDeptId == 1) {
						this.showUnderGraduateDialog = true;
						Object.keys(this.underGraduateCourseForm).forEach(
							key => {
								if (response.data[key] || response.data[key] === 0) {
									this.underGraduateCourseForm[key] =
										response.data[key];
								}else {
									this.underGraduateCourseForm[key] = "";	
							   }
							}
						);
						this.underGraduateCourseForm["isElective"] =
							response.data["isElective"];
					} else {
						this.changeNatureEdit(response.data.nature);
						Object.keys(this.courseForm).forEach(key => {
							if (response.data[key] || response.data[key] === 0) {
								this.courseForm[key] = response.data[key];
							}else {
								this.courseForm[key] = "";	
							}
							
							this.courseForm["isElective"] =
								response.data["isElective"];
						});
						this.courseForm.id = this.editCourseId;
						if (this.courseForm.college) {
							this.changeDialogCollege(this.courseForm.college);
						}
						this.headTeacherCondition = {
							codeList: [this.courseForm.headTeacher]
						};
						this.teacherCondition = {
							codeList: this.courseForm.teachersList
						};
						if(!this.courseForm.teachersList){
							this.courseForm.teachersList=[]
						}
						//this.showDialog = true;
						this.managerDeptId = this.queryForm.managerDeptId;
						if (type == "edit") {
							this.heardTitle = this.$t("course.updateCourse");
							this.pathKey = "edit";
							this.auto = false;
						} else if (type == "detail") {
							this.heardTitle = this.$t("course.courseDetails");
							this.pathKey = "check";
							this.auto = true;
						}
					}
				}
			});
		},
		//培养方案
		queryScheme(code) {
			this.pathKey = "schemes";
			this.heardTitle = this.$t("course.ofScheme");
			this.code = code;
		},
		//单行删除
		courseDelete(row) {
			
			// this.$confirm(
			// 	this.$t("course.confirmDeleteTip"),
			// 	this.$t("message.prompt"),
			// 	{
			// 		confirmButtonText: this.$t("message.confirm"),
			// 		cancelButtonText: this.$t("message.cancel"),
			// 		type: "warning"
			// 	}
		 this.$delConfirm().then(() => {
				this.confirmDelete({ idSet: [row.id] });
			});
		},
		//确定删除
		confirmDelete(data) {
			deleteCourse(data).then(response => {
				if (response.code == 200) {
					this.$message({
						type: "success",
						message: this.$t("common.tips.deleteSuccess")
					});
					this.onSubmit();
				} else {
					throw response.code;
				}
			});
		},
		showAddDialog() {
			if (this.queryForm.managerDeptId == 1) {
				this.isUpdate = false;
				this.dialogTitle = this.$t("course.addCourse");
				this.editCourseId = "";
				this.readOnly = false;
				this.showUnderGraduateDialog = true;
				this.underAuto = false;
			} else {
				this.heardTitle = this.$t("course.addCourse");
				this.managerDeptId = this.queryForm.managerDeptId;
				this.courseForm = JSON.parse(JSON.stringify(defaultCourseForm));
				this.pathKey = "add";
				this.auto = false;
				// this.doPing();
			}
		},
		doPing() {
			pingSession().then(res => {
				if (res.code == 200 && this.showDialog) {
					setTimeout(() => {
						this.doPing();
					}, 1000 * 60);
				}
			});
		},
		saveUpload() {
			if (_.isEmpty(this.templateList)) {
				this.$message({
					type: "info",
					message: this.$t("message.selectFilePlease")
				});
				return;
			}			
			this.$refs.myUpload.submit();
		},
		autoCode() {
			let trainingLevel = "";
			let college = "";
			if (this.queryForm.managerDeptId == 1) {
				trainingLevel = this.underGraduateCourseForm.trainingLevel;
				college = this.underGraduateCourseForm.college;
			} else {
				trainingLevel = this.courseForm.trainingLevel;
				college = this.courseForm.college;
			}
			if (!trainingLevel) {
				return this.$message({
					type: "error",
					message: this.$t("course.selectTrainingLevel")
				});
			}
			if (!college) {
				return this.$message({
					type: "error",
					message: this.$t("course.selectCollege")
				});
			}
			this.autoCodeInfo.trainingLevel = trainingLevel;
			this.autoCodeInfo.managerDeptId = this.queryForm.managerDeptId;
			this.autoCodeInfo.college = college;
			autoCode(this.autoCodeInfo).then(res => {
				if (res.code == 200) {
					if (this.queryForm.managerDeptId == 1) {
						this.underGraduateCourseForm.code = res.data;
						this.$refs.courseFormCode2.focus();
						// } else {
						// 	this.courseForm.code = res.data;
						// 	this.$refs.courseFormCode.focus();
					}
				}
			});
		},
		//保存课程
		saveCourse() {
			this.$refs.courseForm.validate(valid => {
				if (!valid) {
					this.$message({
						type: "error",
						message: this.$t("course.courseInfoWriteError")
					});
					return;
				}
				let obj = _.cloneDeep(this.courseForm);
				if (obj.establishOn) {
					obj.establishOn = Number(new Date(obj.establishOn));
				}
				obj.managerDeptId = this.queryForm.managerDeptId;
				if (this.editCourseId) {
					obj.id = this.editCourseId;
					editCourse(obj).then(response => {
						if (response.code == 200) {
							this.showDialog = false;
							this.$message({
								type: "success",
								message: this.$t("message.saveSuccess")
							});
							this.onSubmit();
						}
					});
				} else {
					addCourse(obj).then(response => {
						if (response.code == 200) {
							this.showDialog = false;
							this.$message({
								type: "success",
								message: this.$t("message.saveSuccess")
							});
							this.onSubmit();
						}
					});
				}
			});
		},
		cancelUploadDialog() {
			this.showUploadDialog = false;
			this.templateClearFiles();
		},
		templateClearFiles() {
			this.$refs.myUpload.clearFiles();
			this.$nextTick(()=>{
				this.showRemoveConfirm=true;
			})
		},
		exportExcel() {
			let loading = this.$loading({
				lock: true,
				text: "Loading",
				spinner: "el-icon-loading",
				background: "rgba(255, 255, 255, .48)"
			});
			let data=_.cloneDeep(this.queryForm);
            data.idSet = this.chooseCourses.map(c => c.id);
			generateExcel(data).then(res => {
				if (res.code == 200) {
					this.delayRequest(res.data.key, loading);
				}
			});
		},
		async delayRequest(key, loading ) {
			await new Promise(resolve => setTimeout(resolve, 5000));
			examinationStudentsApi.getReportStatus(key)
				.then(res => {
					if (res.code == 200 && res.data.status) {
						loading.close();
						let path = examinationStudentsApi.exportUrl + res.data.path;
                        window.location.href = path;
					} else {
						this.delayRequest(key, loading);
					}
				})
				.catch(err => {
					loading.close();
					throw err;
				});
		},
		getNameByLanguage(obj) {
			let lang = this.$store.getters.language || "cn";
			if (lang == "cn") {
				return obj.name;
			} else {
				return obj.nameEn;
			}
		},
		changeDialogCollege(val) {
			findListByFaculty(val).then(res => {
				this.options.teacherList = res.data;
			});
		},
		resetUnderFormValidate() {
			this.checking = false;
			// 清除表单校验
			this.$refs.underGraduateCourseForm.clearValidate();
			this.underGraduateCourseForm.code = "";
			this.underGraduateCourseForm.college = "";
			this.underGraduateCourseForm.name = "";
			this.underGraduateCourseForm.nameEn = "";
			this.underGraduateCourseForm.credits = "";
			this.underGraduateCourseForm.period = "";
			this.underGraduateCourseForm.isElective = 0;
			this.underGraduateCourseForm.weekHour = "";
			this.underGraduateCourseForm.weeks = "";
			this.underGraduateCourseForm.checked = true;
			this.underGraduateCourseForm.createdAt = "";
			this.underGraduateCourseForm.updatedAt = "";
		},
		//保存本科生课程
		saveUnderGraduateCourse() {
			this.$refs.underGraduateCourseForm.validate(valid => {
				if (!valid) {
					this.$message({
						type: "error",
						message: this.$t("course.courseInfoWriteError")
					});
					return;
				}
				this.checking = false;
				let fn = response => {
					if (response.code == 200) {
						this.showUnderGraduateDialog = false;
						this.$message({
							type: "success",
							message: this.$t("message.saveSuccess")
						});
						this.onSubmit();
					}
				};
				if (this.editCourseId) {
					let obj = _.cloneDeep(this.underGraduateCourseForm);
					obj.id = this.editCourseId;
					editCourse(obj).then(fn);
				} else {
					addCourse(this.underGraduateCourseForm).then(fn);
				}
			});
		},
		//取消本科生课程对话框
		cancelUnderGraduateCourse() {
			this.showUnderGraduateDialog = false;
		},
		calUnderGraduatePeriod() {
			this.underGraduateCourseForm.period = this.underGraduateCourseForm.weekHour * this.underGraduateCourseForm.weeks;
		},
		checkName(rule, value, callback) {
			if(value){
				callback()
				// checkCourseName(value,this.editCourseId).then(res =>{
				// 	if(res.code == 200){
				// 		if(!res.data){
				// 			callback(new Error(this.$t('course.courseNameExist')));
				// 		}else{
				// 			callback()
				// 		}
				// 	}
				// })
			}else{
				callback(new Error(this.$t('请输入课程名称')));
			}
			// if (this.underGraduateCourseForm.name) {
			// 	this.checking = true;
			// 	//因blur事件优先级高于click，导致click不执行，故延迟执行blur事件
			// 	setTimeout(() => {
			// 		if (!this.checking) {
			// 			return;
			// 		}
			// 		checkCourseName(
			// 			this.underGraduateCourseForm.name,			
			// 		).then(res => {
			// 			if (res.code == 200) {
			// 				if(res.data){
			// 					this.underGraduateCourseForm.checked = true;
			// 				}else{
			// 					this.underGraduateCourseForm.checked = false;
			// 				}
			// 			}
			// 		});
			// 	}, 100);
			// }
		},
		notBlank(rule, value, callback) {
			if (value && value.toString().replace(/^\s+|\s+$/g, "") == "") {
				callback(new Error(this.$t("course.mustNotInputBlank")));
			} else {
				callback();
			}
		},
		handleCommand(command) {
			if (command == "import") {
				this.$refs.uploadDialog.open();
			} else if (command == "download") {
				window.location.href = getDownloadUrl();
			}
		},
		// importFiles() {
		// 	this.$refs.uploadDialog.open();
		// },
		// downFiles() {
		// 	window.location.href = getDownloadUrl();
		// },
		clearFiles() {
			this.$refs.upload.clearFiles();
			this.fileList = [];
		},
		uploadFile() {
			if (_.isEmpty(this.fileList)) {
				this.$message({
					type: "info",
					message: this.$t("message.selectFilePlease")
				});
				return;
			}
			this.$refs.upload.submit();
		},
		uploadDone(res, file, fileList) {
			if (res.code == 200) {				
				this.$refs.uploadDialog.close();
				this.onSubmit();
				//导入课程提示
				if(res.data&&res.data.length>0){
					this.importExistCourseList=res.data;
					this.importDialogVisible=true;
				}else{
					this.$message({
						type: "success",
						message: this.$t("common.tips.uploadSuccess")
					});
				}
			} else {
				this.$message({
					type: "error",
					message: this.$t("common.tips.dataFormatError")
				});
				this.clearFiles();
			}
		},
		onError(err, file, fileList) {
			let msg = JSON.parse(err.message);
			this.$message({
				type: "error",
				message: msg.message
			});
		},

		beforeRemove(file, fileList) {
			return this.$confirm(
				this.$t("common.upload.remove") + ` ${file.name}？`
			);
		},
		beforeAvatarUpload(file) {
			let extName = file.name
				.substring(file.name.indexOf(".") + 1)
				.toLowerCase()
				.trim();
			if (!(extName === "xls" || extName === "xlsx")) {
				this.$message({
					type: "error",
					message: this.$t("common.upload.unSupportesFileType")
				});
				this.clearFiles();
				return;
			}
			if (!(file.size / 1024 / 1024 < 5)) {
				this.$message({
					type: "error",
					message: this.$t("common.upload.sizeLimit5M")
				});
				this.clearFiles();
				return;
			}
			this.uploading=true;
		},

		beforeTemplateUploadUpload(file) {
			let extName = file.name
				.substring(file.name.indexOf(".") + 1)
				.toLowerCase()
				.trim();
			if (!(extName === "doc" || extName === "docx")) {
				this.$message({
					type: "error",
					message: this.$t("common.upload.unSupportesFileType")
				});
				this.showRemoveConfirm=false;
				this.templateClearFiles();
				return false;
			}
			if (!(file.size / 1024 / 1024 < 3)) {
				this.$message({
					type: "error",
					message: this.$t("common.upload.sizeLimit3M")
				});
				this.showRemoveConfirm=false;
				this.templateClearFiles();
				return false;
			}
		},
		beforeTemplateUploadRemove(file, fileList) {
			if(this.showRemoveConfirm){
				return this.$confirm(
					this.$t("common.upload.remove") + `？`
				);
			}
			this.templateList=[];
		}
	}
};
</script>

<style lang="scss" scoped>
.gCourseAddDialog {
	div.el-dialog__body {
		max-height: 400px;
		overflow: auto;
	}
	.el-col {
		padding-left: 10px;
		padding-right: 10px;
	}
}
.gCourseAddDialog2 {
	div.el-dialog__body {
		max-height: 500px;
		overflow: auto;
	}
	.el-col {
		padding-left: 10px;
		padding-right: 10px;
	}
}
.file-list {
	margin-top: 8px;
	.item-group {
		float: left;
		font-size: 12px;
		.label {
			width: 140px;
		}
		label {
			display: inline-block;
			vertical-align: top;
			line-height: 32px;
		}
		.span {
			display: inline-block;
			vertical-align: top;
			line-height: 32px;
		}
	}
}
.upload-demo{
	::v-deep .el-upload-list__item-name{
		width:230px;
	}
}
.time{
	float:left;
	margin:5px 0 0 10px;
	&>div:first-child{
		color:red;float:left
	}
	&>div:last-child{
		float:left
	}
	span{
		margin-left:10px;
	}
}
</style>